import { defineStore } from 'pinia'

// 生成随机数据的工具函数
const generateRandomData = {
  // 生成随机IP地址
  ip: () => {
    return `192.168.${Math.floor(Math.random() * 255)}.${Math.floor(Math.random() * 255)}`
  },

  // 生成随机时间（最近30天内）
  time: () => {
    const now = new Date()
    const randomDays = Math.floor(Math.random() * 30)
    const randomHours = Math.floor(Math.random() * 24)
    const randomMinutes = Math.floor(Math.random() * 60)
    now.setDate(now.getDate() - randomDays)
    now.setHours(randomHours)
    now.setMinutes(randomMinutes)
    return now.toISOString()
  },

  // 生成随机状态
  status: () => {
    return Math.random() > 0.2 ? 'running' : 'stopped'
  },

  // 生成随机资源使用率
  usage: () => {
    return Math.floor(Math.random() * 100)
  },

  // 生成随机集群名称
  clusterName: () => {
    const prefixes = ['生产', '测试', '开发', '预发布', '灰度', '灾备']
    const suffixes = ['集群', '环境', '中心', '平台']
    const prefix = prefixes[Math.floor(Math.random() * prefixes.length)]
    const suffix = suffixes[Math.floor(Math.random() * suffixes.length)]
    const number = Math.floor(Math.random() * 5) + 1
    return `${prefix}${suffix}${number}`
  },

  // 生成随机节点名称
  nodeName: (clusterName) => {
    const prefixes = ['计算', '存储', '网络', '应用', '数据库', '缓存']
    const regions = ['北京', '上海', '广州', '深圳', '杭州', '成都']
    const prefix = prefixes[Math.floor(Math.random() * prefixes.length)]
    const region = regions[Math.floor(Math.random() * regions.length)]
    const number = Math.floor(Math.random() * 100) + 1
    return `${clusterName}-${region}-${prefix}${number}`
  },

  // 生成随机实例名称
  instanceName: (nodeName) => {
    const services = ['web', 'app', 'db', 'cache', 'mq', 'es', 'redis', 'nginx', 'tomcat', 'jenkins']
    const envs = ['prod', 'test', 'dev', 'staging']
    const service = services[Math.floor(Math.random() * services.length)]
    const env = envs[Math.floor(Math.random() * envs.length)]
    const number = Math.floor(Math.random() * 100) + 1
    return `${nodeName}-${service}-${env}-${number}`
  }
}

// 生成模拟数据
const generateMockData = () => {
  // 生成集群数据
  const clusters = []
  const clusterCount = Math.floor(Math.random() * 2) + 2 // 2-3个集群
  for (let i = 0; i < clusterCount; i++) {
    const name = generateRandomData.clusterName()
    clusters.push({
      id: i + 1,
      name,
      description: `${name}用于${name.includes('生产') ? '生产环境' : name.includes('测试') ? '测试环境' : '开发环境'}的集群`,
      created_by: 'admin',
      created_at: generateRandomData.time()
    })
  }

  // 生成节点数据
  const nodes = []
  clusters.forEach(cluster => {
    const nodeCount = Math.floor(Math.random() * 5) + 3 // 每个集群3-7个节点
    for (let i = 0; i < nodeCount; i++) {
      const name = generateRandomData.nodeName(cluster.name)
      nodes.push({
        id: nodes.length + 1,
        name,
        cluster: cluster.id,
        cluster_name: cluster.name,
        ip_address: generateRandomData.ip(),
        status: generateRandomData.status(),
        cpu_cores: Math.pow(2, Math.floor(Math.random() * 4) + 2), // 4, 8, 16, 32
        memory_gb: Math.pow(2, Math.floor(Math.random() * 4) + 3), // 8, 16, 32, 64
        disk_gb: Math.pow(2, Math.floor(Math.random() * 4) + 8), // 256, 512, 1024, 2048
        created_by: 'admin',
        created_at: generateRandomData.time()
      })
    }
  })

  // 生成实例数据
  const instances = []
  nodes.forEach(node => {
    const instanceCount = Math.floor(Math.random() * 10) + 5 // 每个节点5-14个实例
    for (let i = 0; i < instanceCount; i++) {
      const name = generateRandomData.instanceName(node.name)
      instances.push({
        id: instances.length + 1,
        name,
        node: node.id,
        node_name: node.name,
        status: generateRandomData.status(),
        cpu_cores: Math.pow(2, Math.floor(Math.random() * 3)), // 1, 2, 4
        memory_gb: Math.pow(2, Math.floor(Math.random() * 3) + 1), // 2, 4, 8
        disk_gb: Math.pow(2, Math.floor(Math.random() * 3) + 4), // 32, 64, 128
        created_by: 'admin',
        created_at: generateRandomData.time()
      })
    }
  })

  // 生成统计数据
  const stats = {
    totalClusters: clusters.length,
    totalNodes: nodes.length,
    totalInstances: instances.length,
    resourceUsage: Math.floor(Math.random() * 30) + 40 // 40-70%的资源使用率
  }

  // 生成负载分布
  const loadDistribution = {
    normal: Math.floor(Math.random() * 5) + 3,
    warning: Math.floor(Math.random() * 3) + 1,
    critical: Math.floor(Math.random() * 2)
  }

  // 生成最近活动
  const recentActivities = []
  const activityTypes = ['info', 'success', 'warning', 'error']
  const activityContents = [
    '创建实例',
    '删除实例',
    '启动实例',
    '停止实例',
    '添加节点',
    '移除节点',
    '创建集群',
    '删除集群'
  ]

  for (let i = 0; i < 20; i++) {
    const type = activityTypes[Math.floor(Math.random() * activityTypes.length)]
    const content = activityContents[Math.floor(Math.random() * activityContents.length)]
    const resource = instances[Math.floor(Math.random() * instances.length)]
    recentActivities.push({
      id: `activity_${i}`,
      type,
      timestamp: generateRandomData.time(),
      content: `${content}: ${resource.name}`
    })
  }

  // 生成资源使用趋势
  const resourceUsage = []
  const now = new Date()
  for (let i = 0; i < 24; i++) {
    const time = new Date(now)
    time.setHours(now.getHours() - i)
    resourceUsage.unshift({
      timestamp: time.toISOString(),
      cpu_usage: generateRandomData.usage(),
      memory_usage: generateRandomData.usage(),
      disk_usage: generateRandomData.usage()
    })
  }

  return {
    clusters,
    nodes,
    instances,
    stats,
    loadDistribution,
    recentActivities,
    resourceUsage
  }
}

// 生成初始模拟数据
const mockData = generateMockData()

export const useCloudStore = defineStore('cloud', {
  state: () => ({
    clusters: mockData.clusters,
    nodes: mockData.nodes,
    instances: mockData.instances,
    stats: mockData.stats,
    loadDistribution: mockData.loadDistribution,
    recentActivities: mockData.recentActivities,
    resourceUsage: mockData.resourceUsage,
    loading: false,
    error: null
  }),

  actions: {
    // 集群相关操作
    async fetchClusters() {
      this.loading = true
      try {
        await new Promise(resolve => setTimeout(resolve, 500))
        this.clusters = mockData.clusters
      } catch (error) {
        this.error = error.message
      } finally {
        this.loading = false
      }
    },

    async createCluster(data) {
      try {
        await new Promise(resolve => setTimeout(resolve, 500))
        const newCluster = {
          id: this.clusters.length + 1,
          ...data,
          created_by: 'admin',
          created_at: new Date().toISOString()
        }
        this.clusters.push(newCluster)
        return newCluster
      } catch (error) {
        this.error = error.message
        throw error
      }
    },

    async updateCluster(id, data) {
      try {
        await new Promise(resolve => setTimeout(resolve, 500))
        const index = this.clusters.findIndex(c => c.id === id)
        if (index !== -1) {
          this.clusters[index] = { ...this.clusters[index], ...data }
        }
        return this.clusters[index]
      } catch (error) {
        this.error = error.message
        throw error
      }
    },

    async deleteCluster(id) {
      try {
        await new Promise(resolve => setTimeout(resolve, 500))
        this.clusters = this.clusters.filter(c => c.id !== id)
      } catch (error) {
        this.error = error.message
        throw error
      }
    },

    // 节点相关操作
    async fetchNodes() {
      this.loading = true
      try {
        await new Promise(resolve => setTimeout(resolve, 500))
        this.nodes = mockData.nodes
      } catch (error) {
        this.error = error.message
      } finally {
        this.loading = false
      }
    },

    async createNode(data) {
      try {
        await new Promise(resolve => setTimeout(resolve, 500))
        const newNode = {
          id: this.nodes.length + 1,
          ...data,
          cluster_name: this.clusters.find(c => c.id === data.cluster)?.name || '',
          created_by: 'admin',
          created_at: new Date().toISOString()
        }
        this.nodes.push(newNode)
        return newNode
      } catch (error) {
        this.error = error.message
        throw error
      }
    },

    async updateNode(id, data) {
      try {
        await new Promise(resolve => setTimeout(resolve, 500))
        const index = this.nodes.findIndex(n => n.id === id)
        if (index !== -1) {
          this.nodes[index] = { ...this.nodes[index], ...data }
        }
        return this.nodes[index]
      } catch (error) {
        this.error = error.message
        throw error
      }
    },

    async deleteNode(id) {
      try {
        await new Promise(resolve => setTimeout(resolve, 500))
        this.nodes = this.nodes.filter(n => n.id !== id)
      } catch (error) {
        this.error = error.message
        throw error
      }
    },

    // 实例相关操作
    async fetchInstances() {
      this.loading = true
      try {
        await new Promise(resolve => setTimeout(resolve, 500))
        this.instances = mockData.instances
      } catch (error) {
        this.error = error.message
      } finally {
        this.loading = false
      }
    },

    async createInstance(data) {
      try {
        await new Promise(resolve => setTimeout(resolve, 500))
        const newInstance = {
          id: this.instances.length + 1,
          ...data,
          node_name: this.nodes.find(n => n.id === data.node)?.name || '',
          created_by: 'admin',
          created_at: new Date().toISOString()
        }
        this.instances.push(newInstance)
        return newInstance
      } catch (error) {
        this.error = error.message
        throw error
      }
    },

    async updateInstance(id, data) {
      try {
        await new Promise(resolve => setTimeout(resolve, 500))
        const index = this.instances.findIndex(i => i.id === id)
        if (index !== -1) {
          this.instances[index] = { ...this.instances[index], ...data }
        }
        return this.instances[index]
      } catch (error) {
        this.error = error.message
        throw error
      }
    },

    async deleteInstance(id) {
      try {
        await new Promise(resolve => setTimeout(resolve, 500))
        this.instances = this.instances.filter(i => i.id !== id)
      } catch (error) {
        this.error = error.message
        throw error
      }
    },

    async startInstance(id) {
      try {
        await new Promise(resolve => setTimeout(resolve, 500))
        const index = this.instances.findIndex(i => i.id === id)
        if (index !== -1) {
          this.instances[index].status = 'running'
        }
      } catch (error) {
        this.error = error.message
        throw error
      }
    },

    async stopInstance(id) {
      try {
        await new Promise(resolve => setTimeout(resolve, 500))
        const index = this.instances.findIndex(i => i.id === id)
        if (index !== -1) {
          this.instances[index].status = 'stopped'
        }
      } catch (error) {
        this.error = error.message
        throw error
      }
    },

    // 仪表盘相关操作
    async fetchStats() {
      try {
        await new Promise(resolve => setTimeout(resolve, 500))
        this.stats = mockData.stats
      } catch (error) {
        this.error = error.message
        throw error
      }
    },

    async fetchLoadDistribution() {
      try {
        await new Promise(resolve => setTimeout(resolve, 500))
        this.loadDistribution = mockData.loadDistribution
      } catch (error) {
        this.error = error.message
        throw error
      }
    },

    async fetchRecentActivities() {
      try {
        await new Promise(resolve => setTimeout(resolve, 500))
        this.recentActivities = mockData.recentActivities
      } catch (error) {
        this.error = error.message
        throw error
      }
    },

    // 资源使用监控
    async fetchResourceUsage() {
      try {
        await new Promise(resolve => setTimeout(resolve, 500))
        this.resourceUsage = mockData.resourceUsage
      } catch (error) {
        this.error = error.message
        throw error
      }
    }
  }
}) 